package com.yuandian.api.customer_perception.vo;

import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类说明: 告警类型比例
 *
 * @Date 2021/8/16 9:10
 * @Author User
 */

@Getter
@Setter
public class AlarmTypeRateVo {

    /**
     * 告警类型
     */
    private String alarmType;

    /**
     * 告警数
     */
    private Integer alarmCount;

    /**
     * 告警类型比例
     */
    private Integer alarmRate;

    /**
     * 告警详情列表
     */
    private List<AlarmTypeDetail> alarmDetail;


    /**
     * 构造告警详情比例和列表
     *
     * @param rate 比例数据
     * @param detail 详情数据
     */
    public static List<AlarmTypeRateVo> build (List<AlarmTypeProportionVo> rate, List<AlarmTypeProportionVo> detail) {
        List<AlarmTypeRateVo> result = new ArrayList<>();
        if (null == rate) {
            return result;
        }

        Map<String, List<AlarmTypeProportionVo>> detailMap = new HashMap<>();
        detail.forEach(item -> {
            List<AlarmTypeProportionVo> tmp = detailMap.computeIfAbsent(item.getAlarmType(), k-> new ArrayList<>());
            tmp.add(item);
        });

        // 总告警数
        int totalAlarmCount = 0;
        for (AlarmTypeProportionVo item : rate) {
            totalAlarmCount += item.getAlarmCount();
        }


        // 构造告警比例
        for (AlarmTypeProportionVo item : rate) {
            AlarmTypeRateVo rateVo = new AlarmTypeRateVo();
            rateVo.setAlarmType(item.getAlarmType());
            rateVo.setAlarmCount(item.getAlarmCount());
            rateVo.setAlarmRate(item.getAlarmCount() / totalAlarmCount * 100);

            rateVo.setAlarmDetail(AlarmTypeDetail.build(detailMap.get(item.getAlarmType())));
            result.add(rateVo);
        }

        return result;
    }


    @Getter
    @Setter
    public static class AlarmTypeDetail {
        /**
         * 告警名称
         */
        private String alarmName;

        /**
         * 告警数
         */
        private Integer alarmCount;

        public static List<AlarmTypeDetail> build (List<AlarmTypeProportionVo> detail) {
            List<AlarmTypeDetail> result = new ArrayList<>();
            if (null == detail) {
                return result;
            }

            detail.sort((a,b) -> b.getAlarmCount().compareTo(a.getAlarmCount()));
            detail = detail.subList(0, Math.min(5, detail.size()));

            detail.forEach(item -> {
                AlarmTypeDetail typeDetail = new AlarmTypeDetail();
                typeDetail.setAlarmName(item.getAlarmTypeName());
                typeDetail.setAlarmCount(item.getAlarmCount());

                result.add(typeDetail);
            });

            return result;
        }
    }

}
